use tokio::net::TcpListener;

pub mod ffi;
pub mod tcp;
pub mod websocket;
pub mod keyboard;
pub mod config;


/**
 * TCP server
 */

pub async fn tcp_server(tcp_addr: &str) -> anyhow::Result<()> {
    let listener = TcpListener::bind(tcp_addr).await?;
    log::debug!("TCP server running on port:{}", tcp_addr);

    loop {
        match listener.accept().await {
            Ok((stream, addr)) => {
                let result = tcp::tcp::Server::new().handler_client(stream, addr).await;
                if let Err(e) = result {
                    log::debug!("ip -> {}  handler error -> {}", addr, e);
                }
            }
            Err(err) => {
                log::debug!("connection error {}", err);
            }
        }
    }
}


/// WEBSOCKET server
pub async fn websocket_server(ws_addr: &str) -> anyhow::Result<()> {
    let server = TcpListener::bind(ws_addr).await.unwrap();
    log::debug!("WEBSOCKET server running on port:{}", ws_addr);

    while let Ok((stream, addr)) = server.accept().await {
        tokio::spawn(websocket::websocket::Websocket::accept_connection(stream, addr));
    }
    Ok(())
}
